package top.zimang.loveforwords.Task;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import top.zimang.loveforwords.Listener.DownloadListener;

public class Download extends AsyncTask<String,Integer,Integer> {
    public static final int TYPE_SUCCESS=0;
    public static final int TYPE_FAIED=1;
    private String url;
    private DownloadListener listener;

    public Download(DownloadListener listener) {
        this.listener = listener;
    }

    @Override
    protected Integer doInBackground(String... strings) {
        String directory= Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath();
        File dir = new File(directory+"/loveForWords/pron/");
        try{
            if(dir.exists()||dir.mkdirs()) {
                Log.i("dir","Ok");
            } else {
                Log.i("dir","NotOk");
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        InputStream is=null;
        RandomAccessFile mp3File=null;
        String s=strings[0];
        url=s;
        long downloadedLength=0;
        long contentLength=getContentLength(s);
        File file=null;
        try {
            String fileName=s.substring(s.lastIndexOf("/"));
            file=new File(directory+"/loveForWords/pron/"+fileName);

            if (file.exists()) downloadedLength = file.length();
            if (contentLength==0){
                return TYPE_FAIED;
            }else if(contentLength==downloadedLength){
                //已下载字节和文字总字节相等，说明下载完成
                return TYPE_SUCCESS;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .addHeader("RANGE","bytes="+downloadedLength+"-")
                .url(s)
                .build();
        Response response= null;
        try {
            response = client.newCall(request).execute();
            if(response!=null){
                is=response.body().byteStream();
                mp3File=new RandomAccessFile(file,"rw");
                byte[] b=new byte[1024];
                mp3File.seek(downloadedLength);
                int len=0;
                while ((len=is.read(b))!=-1){
                    mp3File.write(b,0,len);
                }
                response.body().close();
                return TYPE_SUCCESS;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (is!=null){
                    is.close();
                }
                if (mp3File!=null){
                    mp3File.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return TYPE_SUCCESS;
    }
    @Override
    protected void onPostExecute(Integer integer) {
        switch (integer){
            case TYPE_FAIED:
                listener.onFailed();
                break;
            case TYPE_SUCCESS:
                listener.onSuccess();
                break;
            default:
                break;

        }
    }
    private Long getContentLength(String downloadUrl) {
        long contentLength=0;
        OkHttpClient client=new OkHttpClient();
        Request request=new Request.Builder()
                .url(downloadUrl)
                .build();
        Response response= null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if(response!=null&&response.isSuccessful()){
            contentLength=response.body().contentLength();
            response.cacheResponse();
        }
        return contentLength;
    }
}
